package com.yuexun.beilunpatient.ui.satisfaction.ui;

import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseEntity;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.satisfaction.adapter.SatisfactionTopicAdapter;
import com.yuexun.beilunpatient.ui.satisfaction.bean.SatisfactionAnswerDtlBean;
import com.yuexun.beilunpatient.ui.satisfaction.bean.SatisfactionDtlBean;
import com.yuexun.beilunpatient.ui.satisfaction.bean.StartSatisfactionBean;
import com.yuexun.beilunpatient.ui.satisfaction.bean.UpdateSatisfactionBean;
import com.yuexun.beilunpatient.ui.satisfaction.model.impl.SatisfactionModel;
import com.yuexun.beilunpatient.ui.satisfaction.presenter.impl.SatisfactionDtlPresenter;
import com.yuexun.beilunpatient.ui.satisfaction.presenter.impl.StartSatisfactionPresenter;
import com.yuexun.beilunpatient.ui.satisfaction.presenter.impl.UpdateSatisfactionPresenter;
import com.yuexun.beilunpatient.ui.satisfaction.ui.view.ISatisfactionDtlView;
import com.yuexun.beilunpatient.ui.satisfaction.ui.view.IStartSatisfactionView;
import com.yuexun.beilunpatient.ui.satisfaction.ui.view.IUpdateSatisfactionView;
import com.yuexun.beilunpatient.widget.ActionSheetDialog;
import com.yuexun.beilunpatient.widget.FlowLayout;
import com.yuexun.beilunpatient.widget.FlowRadioGroup;
import com.yuexun.beilunpatient.widget.LinearLayoutForListView;
import com.yuexun.beilunpatient.widget.ToastDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/4/12 0012.
 */

public class Act_Satisfaction_Start extends BaseKJActivity implements IStartSatisfactionView, ISatisfactionDtlView, IUpdateSatisfactionView {

    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.ib_right)
    TextView ibRight;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.tv_template_name)
    TextView tvTemplateName;
    @Bind(R.id.tv_y_time)
    TextView tvTime;
    @Bind(R.id.tv_area)
    TextView tvArea;
    @Bind(R.id.tv_unit)
    TextView tvUnit;
    @Bind(R.id.tv_people)
    TextView tvPeople;
    @Bind(R.id.tv_d_people)
    TextView tvDPeople;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.tv_identity)
    TextView tvIdentity;
    @Bind(R.id.tv_health_id)
    TextView tvHealthId;
    @Bind(R.id.tv_phone)
    TextView tvPhone;
    @Bind(R.id.ll_used_time)
    LinearLayout ll_used_time;
    @Bind(R.id.tv_used_time)
    TextView tv_used_time;
    @Bind(R.id.topic_list)
    LinearLayoutForListView topicLayout;

    //get：我收到的、草稿箱  submit：我提交的
    private String type = "";
    private int templateId;
    private int satisfactionId;
    private String createName;
    StartSatisfactionPresenter startSatisfactionPresenter;
    SatisfactionDtlPresenter dtlPresenter;
    UpdateSatisfactionPresenter updateSatisfactionPresenter;
    private SatisfactionTopicAdapter adapter;
    private int answerId;
    //人员详情
    private SatisfactionAnswerDtlBean satisfactionAnswerDtl;
    //已选题目列表
    private List<SatisfactionAnswerDtlBean.ListBeanX> answerList = new ArrayList<>();
    //题目列表
    private List<SatisfactionDtlBean.DtlListBean> topicList = new ArrayList<>();

    private List<UpdateSatisfactionBean> updateAnswer = new ArrayList<>();

    ToastDialog toastDialog;


    @Override
    public void setRootView() {
        setContentView(R.layout.act_satisfaction_start);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        startSatisfactionPresenter = new StartSatisfactionPresenter(new SatisfactionModel(), this);
        dtlPresenter = new SatisfactionDtlPresenter(new SatisfactionModel(), this);
        updateSatisfactionPresenter = new UpdateSatisfactionPresenter(new SatisfactionModel(), this);
        type = getIntent().getStringExtra("type");
        templateId = getIntent().getIntExtra("templateId", 0);
        satisfactionId = getIntent().getIntExtra("satisfactionId", 0);
        createName = getIntent().getStringExtra("createName");
        if (type.equals("submit")) {
            ibRight.setVisibility(View.GONE);
            ll_used_time.setVisibility(View.VISIBLE);
        }

        toastDialog = new ToastDialog(this, "请稍后...");
        toastDialog.setCanceledOnTouchOutside(false);
        toastDialog.show();

        ApiGetStart();
        ApiGetExamAnswerDtl();
    }

    //开始答卷请求
    private void ApiGetStart() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("satisfactionId", satisfactionId + "");
        startSatisfactionPresenter.startSatisfaction(params);
    }

    //请求答案详情
    private void ApiGetExamAnswerDtl() {
        Map<String, String> params_2 = new HashMap<>();
        params_2.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params_2.put("satisfactionId", satisfactionId + "");
        dtlPresenter.getSatisfactionAnswerDtl(params_2);
    }

    //请求题目详情
    private void ApiGetExamDtl() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("templateId", templateId + "");
        dtlPresenter.getSatisfactionDtl(params);
    }

    //提交答案
    private void ApiForSubmitAnswer(int answerStatus, String dtlJson) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("answerId", answerId + "");
        params.put("answerStatus", answerStatus + "");//1提交答卷 0暂存答卷
        params.put("dtlJson", dtlJson);
        updateSatisfactionPresenter.updateSatisfactionAnswer(params);
    }

    @OnClick({R.id.title_back, R.id.ib_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.ib_right:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date endDate = sdf.parse(satisfactionAnswerDtl.getSatisfactionEndTime());
                    if (new Date().before(endDate)) {
                        showSubmitDialog();
                    } else {
                        ViewInject.toast("调查时间已结束，不能提交");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    //暂存答卷、提交答卷
    private void showSubmitDialog() {
        ActionSheetDialog actionSheetDialog;
        actionSheetDialog = new ActionSheetDialog(this).builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("提交答卷", ActionSheetDialog.SheetItemColor.Red,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                toastDialog.show();
                                if (TextUtils.isEmpty(getAllAnswer(true))) {
                                    ViewInject.toast("有未选择的题目");
                                    toastDialog.dismiss();
                                } else {
                                    ApiForSubmitAnswer(1, getAllAnswer(true));
                                }
                            }
                        })
                .addSheetItem("暂存答卷", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                toastDialog.show();
                                ApiForSubmitAnswer(0, getAllAnswer(false));
                            }
                        });
        actionSheetDialog.show();
    }

    //提取全部答案
    private String getAllAnswer(boolean isAllSelect) {
        updateAnswer.clear();

        final int childcount = topicLayout.getChildCount();
        for (int i = 0; i < childcount; i++) {
            View view = topicLayout.getChildAt(i);
            LinearLayout checkboxGroup = (LinearLayout) view.findViewById(R.id.checkbox_group);
            EditText other = (EditText) view.findViewById(R.id.et_other);

            UpdateSatisfactionBean item = new UpdateSatisfactionBean();
            item.setDtlId(topicList.get(i).getDtlId() + "");

            if (topicList.get(i).getShowType().equals("1") || topicList.get(i).getShowType().equals("3")) {    //单选 / 复选
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    CheckBox checkbox = (CheckBox) checkboxGroup.getChildAt(x);
                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);
                    } else {
                        noSelect++;
                        item_1.setDtlAnswer(-1);
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("2") || topicList.get(i).getShowType().equals("4")) { //单选+其他 / 复选其他
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    CheckBox checkbox = (CheckBox) checkboxGroup.getChildAt(x);
                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);
                    } else {
                        item_1.setDtlAnswer(-1);
                    }
                    if (x == (child_1 - 1) && checkbox.getText().toString().equals("其他") && checkbox.isChecked()) {
                        item_1.setDtlValue(other.getText().toString().trim());
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("5")) {         //文本框
                int child_1 = 1;
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();

                for (int x = 0; x < child_1; x++) {
                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    item_1.setDtlValue(other.getText().toString().trim());
                    listItem.add(item_1);
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("6") || topicList.get(i).getShowType().equals("8")) {//单选+二级单选  多选+二级单选
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    View view1 = checkboxGroup.getChildAt(x);
                    CheckBox checkbox = (CheckBox) view1.findViewById(R.id.checkbox);
                    FlowRadioGroup viewGroup = (FlowRadioGroup) view1.findViewById(R.id.viewGroup);

                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);

                        final int child_2 = viewGroup.getChildCount();
                        List<UpdateSatisfactionBean.ListBean> listItem2 = new ArrayList<>();
                        for (int y = 0; y < child_2; y++) {
                            RadioButton childAt = (RadioButton) viewGroup.getChildAt(y);
                            UpdateSatisfactionBean.ListBean item_2 = new UpdateSatisfactionBean.ListBean();
                            item_2.setDtlId(topicList.get(i).getList().get(x).getList().get(y).getDtlId() + "");
                            if (childAt.isChecked()) {
                                item_2.setDtlAnswer(1);
                            }else {
                                item_2.setDtlAnswer(-1);
                            }

                            listItem2.add(item_2);
                        }

                        item_1.setList(listItem2);
                    } else {
                        noSelect++;
                        item_1.setDtlAnswer(-1);
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            } else if (topicList.get(i).getShowType().equals("7") || topicList.get(i).getShowType().equals("9")) {//单选+二级多选 多选+二级多选
                int child_1 = checkboxGroup.getChildCount();
                List<UpdateSatisfactionBean.ListBean> listItem = new ArrayList<>();
                //未选择项
                int noSelect = 0;
                for (int x = 0; x < child_1; x++) {
                    View view1 = checkboxGroup.getChildAt(x);
                    CheckBox checkbox = (CheckBox) view1.findViewById(R.id.checkbox);
                    FlowLayout viewGroup = (FlowLayout) view1.findViewById(R.id.viewGroup);

                    UpdateSatisfactionBean.ListBean item_1 = new UpdateSatisfactionBean.ListBean();
                    item_1.setDtlId(topicList.get(i).getList().get(x).getDtlId() + "");
                    if (checkbox.isChecked()) {
                        item_1.setDtlAnswer(1);

                        final int child_2 = viewGroup.getChildCount();
                        List<UpdateSatisfactionBean.ListBean> listItem2 = new ArrayList<>();
                        for (int y = 0; y < child_2; y++) {
                            CheckBox childAt = (CheckBox) viewGroup.getChildAt(y);
                            UpdateSatisfactionBean.ListBean item_2 = new UpdateSatisfactionBean.ListBean();
                            item_2.setDtlId(topicList.get(i).getList().get(x).getList().get(y).getDtlId() + "");
                            if (childAt.isChecked()) {
                                item_2.setDtlAnswer(1);
                            }else {
                                item_2.setDtlAnswer(-1);
                            }

                            listItem2.add(item_2);
                        }

                        item_1.setList(listItem2);
                    } else {
                        noSelect++;
                        item_1.setDtlAnswer(-1);
                    }
                    listItem.add(item_1);
                }
                //未选择项 = 总项
                if (isAllSelect && noSelect == child_1) {
                    return null;
                }
                item.setList(listItem);
            }
            updateAnswer.add(item);
        }
        return JSON.toJSONString(updateAnswer);
    }

    @Override
    public void startSatisfaction(BaseEntity<StartSatisfactionBean> bean) {
        if (bean.getStatus().equals("200")) {
            answerId = bean.getDatas().get(0).getAnswerId();
        } else {
            ViewInject.toast("开始答卷失败");
        }
    }

    @Override
    public void getSatisfactionAnswerDtl(BaseEntity<SatisfactionAnswerDtlBean> bean) {
        if (bean.getStatus().equals("200")) {
            satisfactionAnswerDtl = bean.getDatas().get(0);
            answerList = bean.getDatas().get(0).getList();

            ApiGetExamDtl();
            showAnswerDtl();
        } else {
            ViewInject.toast("获取答卷详情错误");
        }
    }

    @Override
    public void getSatisfactionDtl(BaseEntity<SatisfactionDtlBean> bean) {
        if (bean.getStatus().equals("200")) {
            topicList = bean.getDatas().get(0).getDtlList();
            if (type.equals("get")) {
                adapter = new SatisfactionTopicAdapter(this, topicList, true, answerList);
            } else if (type.equals("submit")) {
                adapter = new SatisfactionTopicAdapter(this, topicList, false, answerList);
            }
            topicLayout.setAdapter(adapter);
            toastDialog.dismiss();
        } else {
            ViewInject.toast("获取题目详情错误");
        }
    }

    //显示答案详情
    private void showAnswerDtl() {
        if (type.equals("submit")) {
            titleTv.setText(satisfactionAnswerDtl.getSatisfactionName());
        }
        tvTitle.setText(satisfactionAnswerDtl.getSatisfactionName());
        tvType.setText(satisfactionAnswerDtl.getTypeName());
        tvTemplateName.setText(satisfactionAnswerDtl.getTemplateTitle());
        tvTime.setText(satisfactionAnswerDtl.getSatisfactionStartTime() + "~" + satisfactionAnswerDtl.getSatisfactionEndTime());
        tvArea.setText(satisfactionAnswerDtl.getAreaName());
        tvUnit.setText(satisfactionAnswerDtl.getHospName());
        tvPeople.setText(createName);
        tvDPeople.setText(satisfactionAnswerDtl.getPatientName());
        tvSex.setText(satisfactionAnswerDtl.getSex());
        tvIdentity.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.ID_CARD));
        tvHealthId.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.HEALTHID));
        tvPhone.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.TEL));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(satisfactionAnswerDtl.getSatisfactionStartTime());
            Date endDate = sdf.parse(satisfactionAnswerDtl.getSatisfactionEndTime());
            long l = endDate.getTime() - startDate.getTime();
            long H = l / (1000 * 60) / 60;
            long M = l / (1000 * 60) % 60;
            if (H > 0 && M > 0) {
                tv_used_time.setText(H + "时" + M + "分");
            } else if (H == 0) {
                tv_used_time.setText(M + "分");
            } else if (M == 0) {
                tv_used_time.setText(H + "时");
            } else {
                tv_used_time.setText(M + "分");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateSatisfaction(BaseEntity<String> bean) {
        if ("200".equals(bean.getStatus())) {
            ViewInject.toast("提交成功");
            finish();
        } else {
            ViewInject.toast("提交失败");
        }
        toastDialog.dismiss();
    }
}
